Python: Decorator
関数とクラスに対して適用でき、関数あるいはクラスを指定した関数でラップしたものを返す。@wrapper構文。
Pythonでは関数とクラスがFirst-class Objectである性質を用いている。
実例を見るとわかりやすい。
関数のデコレータの例
code:py
@staticmethod
def f(arg):
...
これは次のコードのシンタックスシュガーであり同等である。
code:py
def f(arg):
...
f = staticmethod(f)
@f1(arg)とすればf1(arg)関数でラップされる。
クラスのデコレータの例
code:py
@f1(arg)
@f2
class Foo: pass
これは以下のコードと同等。
code:py
class Foo: pass
Foo = f1(arg)(f2(Foo))
参考
https://docs.python.org/ja/3/glossary.html#term-decorator
https://docs.python.org/ja/3/reference/compound_stmts.html#function
https://docs.python.org/ja/3/reference/compound_stmts.html#class